import express, { type Request, Response, NextFunction } from "express";
import morgan from "morgan"
import rateLimit from "express-rate-limit"
// import helmet from "helmet"
import cors from "cors"
import xss from "xss-clean"
import imageRouter from "../router/imageRouter.js"
import errorHanlder from "../controller/error.controller.js"
import AppError from "../class/AppError.js";
import { judgeImgVilad } from "../middleware/img.middlerware.js"
import { history } from "../middleware/history.middlerware.js"

const app = express();

// 1) GLOBAL MIDDLEWARE
//    1.1 Development logging
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}
//    1.2 Body parser, reading data from body into req.body
app.use(express.json({ limit: '10kb' }));
//    1.3 Limit request from same IP
const limiter = rateLimit({
  max: 200,
  windowMs: 60 * 1000,
  message: 'Too many request from this IP, please try again after an minute',
})
app.use('/', limiter)
//    1.4 Data sanitization against XSS
app.use(xss())
//    1.5 Set security HTTP headers
// app.use(helmet())
//    1.6 History router
app.use(history({
  matchArr: ['/mine', '/about', '/feedback'],
  index: "/www/dist/index.html"
}))

// 2) ROUTERS
app.use(imageRouter)

// 3) CORS (only for Static assets)
app.use(cors())
// @ts-ignore  针对非简单请求：put、patch、delete或发送 cookie 的请求需要额外设置
app.options('*', cors())

// 4) STATIC FILE
const PUBLIC_PATH = "uploads/"
const PUBLIC_WWW_PATH = "www/dist/"
app.use(express.static(PUBLIC_WWW_PATH));
app.use(judgeImgVilad, express.static(PUBLIC_PATH));

// 5) UNHANDLED ROUTER
app.all('*', (req: Request, res: Response, next: NextFunction) => {
  next(new AppError(404, `Can't find ${req.originalUrl} on this server!`));
});

// 6) ERROR HANDLER
app.use(errorHanlder)


export default app
